﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Mail;
using TVGuide.Common;

namespace TVGuide.Parser
{
    public class HTTPClient
    {

        // Method:
        //     GetSiteContent(string url)
        //
        // Summary:
        //     
        //
        // Parameters:
        //   string url - 
        //
        // Exceptions:
        //    no exceptions   

        /// <summary>
        ///     Gets raw HTML from URL
        /// </summary>
        /// <param name="url">url of the web page, to retrieve cintent froms </param>
        /// <param name="encoding">Encoding that given site is using</param>
        /// <returns>Returns site content </returns>

        public static string GetSiteContent(string url, Encoding encoding, string  channelName)
        {
            int retryCount=2;
            int failedCount = 0;
            bool failed = false;
            string tabClearRawHTML = "";
            do
            {
                if (failedCount > retryCount)
                {
                    failed = true;
                }
                try
                {
                    // At this moment we are not handeling timout situation :(

                    HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(url);
                    HttpWRequest.Method = "GET";
                    HttpWRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11";
                    //HttpWRequest.Connection = "keep-alive";
                    CookieContainer cookCont = new CookieContainer();
                    HttpWRequest.CookieContainer = cookCont;
                    HttpWRequest.AllowAutoRedirect = true;
                    HttpWRequest.MaximumAutomaticRedirections = 200;
                    HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();
                    //Read the raw HTML from the request
                    StreamReader sr = new StreamReader(HttpWResponse.GetResponseStream(), encoding);
                    //Convert the stream to a string
                    var rawHTML = sr.ReadToEnd();
                    sr.Close();

                    Regex rgxRemoveBullshit = new Regex("[\r\n]");
                    //tabClearRawHTML = rgxRemoveBullshit.Replace(rawHTML, "");
                    tabClearRawHTML = (rgxRemoveBullshit.Replace(rawHTML, "")).Replace('\t', ' ').Replace("&ndash;", "-").Replace("&nbsp;", " ");

                    return tabClearRawHTML;

                }
                catch (WebException webEx)
                {
                    failedCount++;
                    Console.WriteLine("Exception during GetSiteContent() method call is - " + webEx.Message);

                }
                catch (System.Exception e)
                {
                    //debuging stuff
                    Console.WriteLine("Exception during GetSiteContent() method call is - " + e.Message);

                }
                finally
                {
                    if (failed)
                    {
                        string message = "Failed to connect to "+channelName;
                        Utils.SendNotificationMail(message);
                    }
                }

            } while (!failed);
            
            return tabClearRawHTML;
        }

        public static string GetSiteContent(string url)
        {
             return GetSiteContent(url, Encoding.Default, "");
        }

        public static String GetSteamToken(string url)
        {
            string data = GetSiteContent(url, Encoding.UTF8, "TV stream URL");
            string streamPattern = "file:'(.*?)'";
            Regex rgx = new Regex(streamPattern, RegexOptions.IgnoreCase);
            if (rgx.IsMatch(data))
            {
                string val = rgx.Match(data).Groups[1].Value;
                return val.Substring(val.IndexOf("?")+1);
            }
            else
            {
                return "";
            }
              
        }


    }
}
